package com.fyl.leetcode.binarySearch;

/**
 * @author:fyl
 * @date 2021/8/25 19:08
 * @Modified By:
 * @Modified Date:
 * @Description: 35
 * 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * 请必须使用时间复杂度为 O(log n) 的算法。
 * 示例 1:
 * 输入: nums = [1,3,5,6], target = 5
 * 输出: 2
 * 示例2:
 * 输入: nums = [1,3,5,6], target = 2
 * 输出: 1
 */
public class SearchInsert {
    public static int searchInsert(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int index = 0;
        if (nums[nums.length - 1] < target) {
            return nums.length;
        }
        while (left <= right) {
            index = left + ((right - left) >> 1);
            if (nums[index] < target) {
                left = index + 1;
            } else if (nums[index] > target) {
                right = index - 1;
            } else {
                return index;
            }
        }
        return Math.max(left, index);
    }

    public static void main(String[] args) {
        int[] num = new int[]{
                1, 3, 5, 6
        };
        System.out.println(searchInsert(num, 2));
    }

    public int mySqrt(int x) {
        int left = 0;
        int right = x / 2;
        while (left <= right) {
            int index = left + ((right - left) >> 1);
            if (Math.pow(index,2) < x) {
                left = index + 1;
            } else if (Math.pow(index,2) > x) {
                right = index - 1;
            } else {
                return index;
            }
        }
        return right;
    }


}
